package org.rslai.tcedit.web.admin;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rslai.tcedit.domain.Product;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 初始化所有产品
 * 
 * @author rslai
 * 
 * @spring.bean name="/admin/initAllProduct.jspx"
 */
public class InitAllProductController extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		String action = HttpUtil.getString(request, "action", "").toLowerCase();

		if (action.equals("initallproduct")) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			try {
				writer.write("<p>正在初始化所有产品，请耐心等待...</p>");
				writer.flush();

				int total = 0;
				List<Product> productList = this.productService.query(true);
				total = productList.size();
				writer.write("<p>产品总数：" + total + "</p>");
				writer.flush();

				writer.write("<p><ol>");
				for (Product product : productList) {
					writer.write("<li>正在初始化产品：" + product.getName() + " ...... </li>");
					writer.flush();

					this.productService.init(product);

					writer.write("成功！");
					writer.flush();
				}

				writer.write("</ol></p>");
				writer.write("<P>初始化产品完成，请关闭本窗口！<br>重新执行编译并重启应用服务器！</P>");
			} catch (Exception e) {
				writer.write("<br><br>错误：" + e.getMessage());
				writer.write("<br><pre>");
				e.printStackTrace(writer);
				writer.write("</pre>");
			}
			writer.flush();
			return null;
		}

		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/admin/initAllProduct.htm";
	}

}
